import { Component, OnInit, HostBinding, ChangeDetectionStrategy, ChangeDetectorRef, OnDestroy } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { NewProjectComponent } from '../new-project/new-project.component';
import { InviteComponent } from '../invite/invite.component';
import { ConfirmDialogComponent } from '../../shared/confirm-dialog/confirm-dialog.component';
import { slideToRight } from '../../anims/router.anima';
import { listAnimation } from '../../anims/list.anima';
import { Project } from '../../domain/index';
import { ProjectService } from '../../services/project.service';
import * as _ from 'lodash';
import { Subscription } from 'rxjs/Subscription';
import { Store } from '@ngrx/store';
import * as fromRoot from '../../reducers';
import { Observable } from 'rxjs/Observable';
import {
  ProjectLoadAction,
  ProjectAddAction,
  ProjectUpdateAction,
  ProjectDeleteAction,
  ProjectSelectAction,
  ProjectInviteAction
} from '../../actions/projects.action';
import { Router } from '@angular/router';
@Component({
  selector: 'app-project-list',
  templateUrl: './project-list.component.html',
  styleUrls: ['./project-list.component.scss'],
  animations: [
    slideToRight,
    listAnimation
  ],
  // 使用onPush 策略
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProjectListComponent implements OnInit, OnDestroy {

  // 绑定触发器
  @HostBinding('@routeAnim') state;

  projects$: Observable<Project[]>;
  listAnim$: Observable<number>;
  constructor(
    private dialog: MatDialog,
    private cd: ChangeDetectorRef,
    private store$: Store<fromRoot.State>,
    private router: Router
    // private service$: ProjectService
  ) { }

  ngOnInit() {
    this.store$.dispatch(new ProjectLoadAction(null));
    this.projects$ = this.store$.select(fromRoot.getProjects);
    this.listAnim$ = this.projects$.map(p => p.length);
  }
  ngOnDestroy(): void {
  }

  selectProject(project: Project) {
    this.store$.dispatch(new ProjectSelectAction(project));
    this.router.navigate([`/tasklists/${project.id}`]);
  }

  openNewProjectDialog() {
    const selectedImg = `/assets/img/covers/${Math.floor(Math.random() * 40)}_tn.jpg`;
    const dialogRef = this.dialog.open(NewProjectComponent,
      {
        data: {
          thumbnails: this.getThumbnails(),
          img: selectedImg
        }
      }
    );
    dialogRef.afterClosed()
      .take(1)
      .filter(n => n)
      .map(val => ({ ...val, coverImg: this.buildImgSrc(val.coverImg) }))
      .subscribe(project => {
        // 当前的加了
        // this.projects = [...this.projects, project];
        this.store$.dispatch(new ProjectAddAction(project));
      });
  }

  launchInviteDialog(project: Project) {
    this.store$.select(fromRoot.getProjectUsers(project.id))
      .map(users => this.dialog.open(InviteComponent, {
        data: {
          members: [users]
        }
      }))
      .switchMap(dialogRef => dialogRef.afterClosed().take(1).filter(n => n))
      .subscribe(val => this.store$.dispatch(new ProjectInviteAction({ projectId: project.id, members: val })));
  }
  launchUpdateDialog(project: Project) {
    const dialogRef = this.dialog.open(NewProjectComponent, {
      data: {
        thumbnails: this.getThumbnails(),
        project: project
      }
    });
    dialogRef.afterClosed()
      .take(1)
      .filter(n => n)
      .map(val => ({ ...val, id: project.id, coverImg: this.buildImgSrc(val.coverImg) }))
      .subscribe(rsproject => {
        this.store$.dispatch(new ProjectUpdateAction(rsproject));
        // 在这个时候进行内部检测
        // this.cd.markForCheck();
      });
  }
  launchConfirmDialog(project) {
    const dialogRef = this.dialog.open(ConfirmDialogComponent,
      {
        data: {
          title: '删除项目',
          content: '您确定删除该项目吗?'
        }
      }
    );
    dialogRef.afterClosed()
      .take(1)
      .filter(n => n)
      // tslint:disable-next-line:no-shadowed-variable
      .subscribe(_ => {
        this.store$.dispatch(new ProjectDeleteAction(project));
        // this.cd.markForCheck();
      });
  }

  private getThumbnails() {
    return _.range(0, 40)
      .map(i => `/assets/img/covers/${i}_tn.jpg`);
  }
  private buildImgSrc(img: string): string {
    return img.indexOf('_') > 1 ? img.split('_')[0] + '.jpg' : img;
  }
}
